package com.imooc.zkjavaapi;

import com.imooc.zkjavaapi.callback.DeleteCallback;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 连接到Zookeeper服务端，打印连接状态
 */
public class ZKGetNode implements Watcher {
    public static final String SERVER_PATH = "127.0.0.1:2181";
    public static final Integer timeout = 5000;

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        /**
         * 客户端和服务端他们是异步连接，连接成功后，客户端会收到watcher通知。
         * connectString: 服务器的IP+端口号，比如127.0.0.1:2128
         * sessionTimeout: 客户端和服务端之间的超时时间，单位毫秒
         * watcher: 监听器，当连接成功后，客户端会收到watcher通知
         */
        ZooKeeper zk = new ZooKeeper(SERVER_PATH, timeout, new ZKGetNode());
        System.out.println("客户端开始连接Zookeeper服务端...");
        System.out.println("连接状态：" + zk.getState());
        Thread.sleep(2000); // 等待20秒，观察连接状态变化
        System.out.println("连接状态：" + zk.getState());
//        zk.create("/imooc","imooc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        /*Stat exists = zk.exists("/imooc", false);
        if (exists != null) {
            System.out.println("节点版本：" + exists.getVersion());
        }else{
            System.out.println("节点不存在");
        }*/
        zk.getData("/imooc", true, null);
        countDownLatch.await();
    }


    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            System.out.println("数据被改变");
            countDownLatch.countDown();
        }
        System.out.println("收到通知：" + watchedEvent);
    }
}
